package backend.project.gym_management.controller;

import backend.project.gym_management.base.config.AliPayConfig;
import backend.project.gym_management.base.response.JsonResult;
import backend.project.gym_management.pojo.dto.UserSelectCourseParam;
import backend.project.gym_management.service.AliPayService;
import backend.project.gym_management.service.UserService;
import backend.project.gym_management.pojo.entity.PayOrder;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/alipay/")
public class AliPayController {
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    private static final String SING_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private UserService userService;

    @GetMapping("pay")
    public void pay(String orderNo, HttpServletResponse httpServletResponse) throws Exception {
        PayOrder payOrder = aliPayService.selectOrder(Long.parseLong(orderNo));
        if (payOrder == null) {
            log.error("订单不存在");
        }

        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SING_TYPE);

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", payOrder.getOid());
        bizContent.put("total_amount", payOrder.getTotal());
        bizContent.put("subject", payOrder.getCname());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        log.debug("bizContent:" + bizContent);
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:9090/gym/course");

        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpServletResponse.setContentType("text/html;charset=" + CHARSET);
        httpServletResponse.getWriter().write(form);
    }

    @PostMapping("notify")
    public void payNotify(HttpServletRequest request) throws Exception {
        String tradeStatus = request.getParameter("trade_status");
        String tradeNo = request.getParameter("out_trade_no");

        // 验证签名
        Map<String,String> params = new HashMap<>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for(String name : requestParams.keySet()){
            params.put(name, request.getParameter(name));
        }

        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSign = AlipaySignature.rsa256CheckContent(content, sign,
                aliPayConfig.getAlipayPublicKey(), "UTF-8");

        if(!checkSign){
            log.error("签名验证失败");
            return;
        }

        PayOrder payOrder = aliPayService.selectOrder(Long.parseLong(tradeNo));
        if(payOrder == null){
            log.error("订单不存在: {}", tradeNo);
            return;
        }

        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            // 支付成功处理
            payOrder.setStatus("支付成功");
            boolean updateResult = aliPayService.updateOrder(payOrder);
            log.info("订单状态更新结果: {}", updateResult);

            // 添加课程逻辑
            UserSelectCourseParam param = new UserSelectCourseParam();
            param.setUid(payOrder.getUid());
            param.setCid(payOrder.getCid());
            param.setUname(aliPayService.getUnameByUid(payOrder.getUid()));

            log.info("开始选课，参数: {}", param);
            try {
                userService.selectCourse(param);
                log.info("选课成功");
            } catch (Exception e) {
                log.error("选课失败，异常信息: ", e);
            }
        } else if("TRADE_CLOSED".equals(tradeStatus)){
            // 交易关闭处理
            payOrder.setStatus("已关闭");
            aliPayService.updateOrder(payOrder);
        }
    }

//    @GetMapping("status")
//    public String checkOrderStatus(@RequestParam String orderNo) {
//        PayOrder order = aliPayService.selectOrder(Long.parseLong(orderNo));
//        return order != null ? order.getStatus() : "订单不存在";
//    }

    @GetMapping("order/exists/{uid}/{cid}")
    public boolean checkOrderExists(@PathVariable Long uid, @PathVariable Long cid) {
        return aliPayService.checkExistingOrder(uid, cid) != null;
    }

    @GetMapping("order/select/{uid}/{cid}")
    public JsonResult selectOrderByUserAndCourse(@PathVariable Long uid, @PathVariable Long cid) {
        PayOrder order = aliPayService.selectOrderByUserAndCourse(uid, cid);
        return JsonResult.ok(order);
    }

    @GetMapping("order/hadCourse/{uid}/{cid}")
    public JsonResult hadCourse(@PathVariable Long uid, @PathVariable Long cid) {
        boolean result = aliPayService.hadCourse(uid, cid);
        if (result) {
            return JsonResult.ok("课程存在");
        } else {
            return JsonResult.ok();
        }
    }
}
